package com.ruoyi.function.controller;

import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.function.domain.TollDataSummary;
import com.ruoyi.function.service.ITollDataSummaryService;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 收费数据汇总Controller
 * 
 * @author ruoyi
 * @date 2025-09-11
 */
@RestController
@RequestMapping("/function/TollDataSummary")
public class TollDataSummaryController extends BaseController
{
    @Autowired
    private ITollDataSummaryService tollDataSummaryService;

    /**
     * 查询收费数据汇总列表
     */
    @PreAuthorize("@ss.hasPermi('function:TollDataSummary:list')")
    @GetMapping("/list")
    public AjaxResult list(TollDataSummary tollDataSummary)
    {
        List<TollDataSummary> list = tollDataSummaryService.selectTollDataSummaryList(tollDataSummary);
        
        // 判断是否有搜索条件，如果有则构建树形结构返回
        boolean hasSearchCondition = tollDataSummary.getRoadName() != null && !tollDataSummary.getRoadName().isEmpty() ||
                                   tollDataSummary.getNodeName() != null && !tollDataSummary.getNodeName().isEmpty();
        
        if (hasSearchCondition) {
            // 有搜索条件时，构建树形结构返回，包含匹配节点及其所有子节点
            List<TollDataSummary> treeList = buildTree(list);
            return success(treeList);
        } else {
            // 无搜索条件时，返回扁平列表
            return success(list);
        }
    }

    /**
     * 导出收费数据汇总列表
     */
    @PreAuthorize("@ss.hasPermi('function:TollDataSummary:export')")
    @Log(title = "收费数据汇总", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TollDataSummary tollDataSummary)
    {
        List<TollDataSummary> list = tollDataSummaryService.selectTollDataSummaryList(tollDataSummary);
        // 过滤出第二层数据，并将第一层的路段名称赋值给第二层
        List<TollDataSummary> secondLevelList = list.stream()
            .filter(item -> item.getParentId() != null && item.getParentId() > 0)
            .map(item -> {
                // 查找父节点并设置路段名称
                list.stream()
                    .filter(parent -> parent.getId().equals(item.getParentId()))
                    .findFirst()
                    .ifPresent(parent -> item.setRoadName(parent.getRoadName()));
                return item;
            })
            .collect(Collectors.toList());
        ExcelUtil<TollDataSummary> util = new ExcelUtil<TollDataSummary>(TollDataSummary.class);
        util.exportExcel(response, secondLevelList, "收费数据汇总数据");
    }

    /**
     * 获取收费数据汇总详细信息
     */
    @PreAuthorize("@ss.hasPermi('function:TollDataSummary:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tollDataSummaryService.selectTollDataSummaryById(id));
    }

    /**
     * 新增收费数据汇总
     */
    @PreAuthorize("@ss.hasPermi('function:TollDataSummary:add')")
    @Log(title = "收费数据汇总", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TollDataSummary tollDataSummary)
    {
        return toAjax(tollDataSummaryService.insertTollDataSummary(tollDataSummary));
    }

    /**
     * 修改收费数据汇总
     */
    @PreAuthorize("@ss.hasPermi('function:TollDataSummary:edit')")
    @Log(title = "收费数据汇总", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TollDataSummary tollDataSummary)
    {
        return toAjax(tollDataSummaryService.updateTollDataSummary(tollDataSummary));
    }

    /**
     * 删除收费数据汇总
     */
    @PreAuthorize("@ss.hasPermi('function:TollDataSummary:remove')")
    @Log(title = "收费数据汇总", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        // 检查是否存在子节点
        for (Long id : ids) {
            if (tollDataSummaryService.hasChildById(id)) {
                return AjaxResult.error("存在下级数据，不允许删除！");
            }
        }
        return toAjax(tollDataSummaryService.deleteTollDataSummaryByIds(ids));
    }
    
    /**
     * 构建树形结构
     */
    private List<TollDataSummary> buildTree(List<TollDataSummary> list) {
        // 构建父子关系映射
        Map<Long, TollDataSummary> nodeMap = new HashMap<>();
        List<TollDataSummary> rootNodes = new ArrayList<>();
        
        // 先将所有节点放入map中
        for (TollDataSummary node : list) {
            nodeMap.put(node.getId(), node);
        }
        
        // 构建父子关系
        for (TollDataSummary node : list) {
            Long parentId = node.getParentId();
            if (parentId != null && parentId != 0) {
                TollDataSummary parent = nodeMap.get(parentId);
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<TollDataSummary>());
                    }
                    @SuppressWarnings("unchecked")
                    List<TollDataSummary> children = (List<TollDataSummary>) parent.getChildren();
                    children.add(node);
                }
            } else {
                rootNodes.add(node);
            }
        }
        
        return rootNodes;
    }
}
